package com.rpm.rpm.login.login;

import com.alibaba.fastjson.JSONObject;
import com.rpm.rpm.constant.ExceptionConstant;
import com.rpm.rpm.mapper.LoginDao;
import com.rpm.rpm.vo.ResultVO;
import com.rpm.rpm.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;

/**
 * 用户注册登录主层
 */
@Service
public class LoginService {

    @Autowired
    private LoginDao dao;

    @Autowired
    private LoginTransService service;

    /**
     * 注册方法
     * @param param
     * @param resultVO
     * @return
     */
    public ResultVO register(JSONObject param,ResultVO resultVO){
        resultVO.setCode(ExceptionConstant.two);
        try{
            //判空方法
            resultVO = service.judgingEmptinessByRegister(param,resultVO);
            if (resultVO.getCode().equals(ExceptionConstant.five)) {
                return resultVO;
            }
            //用户号
            String userCode = param.getString(LoginConstant.userCode);
            //判断用户是否存在
            UserVO userVO = dao.selectUserByUserCode(userCode);
            //已经存在则直接抛错
            if (null != userVO){
                resultVO.setCode(ExceptionConstant.five);
                resultVO.setMessage(ExceptionConstant.badRegister + LoginExceptionConstant.userExists);
                return resultVO;
            }
            //不存在这直接进行新增
            userVO = service.jsonTransByUserVO(null, param);
            dao.insert(userVO);
            resultVO.setMessage(ExceptionConstant.sucessRegister);
        }
        catch (Exception e){
            resultVO.setCode(ExceptionConstant.five);
            resultVO.setMessage(ExceptionConstant.badRegister + e.getMessage());
        }
        return resultVO;
    }

    /**
     * 登录方法
     * @param param
     * @param resultVO
     * @return
     */
    public ResultVO login(JSONObject param,ResultVO resultVO){
        resultVO.setCode(ExceptionConstant.two);
        try {
            //判空方法
            resultVO = service.judgingEmptinessByLogin(param,resultVO);
            if (resultVO.getCode().equals(ExceptionConstant.five)) {
                return resultVO;
            }
            resultVO = service.login(param,resultVO);
            if (resultVO.getCode().equals(ExceptionConstant.five)) {
                return resultVO;
            }
            resultVO.setMessage(ExceptionConstant.sucessLogin);
        }
        catch (Exception e){
            resultVO.setCode(ExceptionConstant.five);
            resultVO.setMessage(ExceptionConstant.badLogin + e.getMessage());
        }
        return resultVO;
    }
}
